package com.liu.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  令牌生成和解析工具
 */
@Data
@ConfigurationProperties("jwt.config")
public class JwtUtil {

    private String key ;

    private long ttl ;//一个小时



    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles", roles);
        if (ttl > 0) {
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }




    private void test(){
        //        JwtBuilder jwtBuilder = Jwts.builder().setId("1164032971834003456")
//                                               .setSubject("小刘")
//                                               .setIssuedAt(new Date())
//                                               .signWith(SignatureAlgorithm.HS256,"liubijun");
//        System.out.println(jwtBuilder.compact());

//        Claims claims = Jwts.parser()
//                .setSigningKey("liubijun").parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMTY0MDMyOTcxODM0MDAzNDU2Iiwic3ViIjoi5bCP5YiYIiwiaWF0IjoxNTY2MzY4ODk2fQ.39RBcIhd0OiVW9BkA_JyBoUyMrRl-eEo-UHuUQ_BC2U").getBody();
//
//        System.out.println("用户ID:"+ claims.getId());
//        System.out.println("用户名称:"+ claims.getSubject());
//        System.out.println("登录时间:"+  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(claims.getIssuedAt()));

    }
}
